package yartiss.engine.simulation.system.taskset;

import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import yartiss.engine.simulation.system.ITask;
import yartiss.engine.simulation.system.ITaskSet;

/**
 * DeadlineTaskSet is a class returns an ordered taskset according to the
 * earliest-deadline-first priority assignment technique
 * @author 
 *
 */
public class DeadlineTaskSet implements ITaskSet {

	private TreeSet<ITask> tasks;
	private long currentDate = 0;
	private int id;
	
	private final Comparator<ITask> comparator = new Comparator<ITask>() {
		@Override
		public int compare(ITask t1, ITask t2) {
			int cmp =  (int) (t1.getNextDeadline(currentDate,false) - t2.getNextDeadline(currentDate,false));
			if(cmp==0)
				return (int) (t1.getPriority() - t2.getPriority());
			return cmp;
		}
	};
	
	
	public DeadlineTaskSet(){
		this.tasks = new TreeSet<ITask>(comparator);
	}
	
	@Override
	public Iterator<ITask> iterator() {
		return tasks.iterator();
	}

	@Override
	public boolean addTask(ITask t) {
		return tasks.add(t);
	}
	
	@Override
	public boolean addTasks(List<ITask> t) {
		return tasks.addAll(t);
	}

	@Override
	public SortedSet<ITask> getActiveTasks(long date) {
		currentDate = date;
		SortedSet<ITask> activeTasks = new TreeSet<ITask>(comparator);
		for (ITask t : tasks)
			if (t.isActive())
				activeTasks.add(t);
		return activeTasks;
	}

	@Override
	public int getAllTasksCount() {
		return tasks.size();
	}

	@Override
	public SortedSet<ITask> getHeadSet(ITask task, boolean inclusive) {
		SortedSet<ITask> activeTasks = new TreeSet<ITask>(comparator);
		return activeTasks;
	}

	@Override
	public int getId() {
		return id;
	}

	@Override
	public int setId(int id) {
		return this.id = id;
	}

	@Override
	public ITask getOne() {
		return tasks.first();
	}
	
	@Override
	public ITaskSet cloneTaskSet() {
		PriorityTaskSet set = new PriorityTaskSet();
		for (ITask task : tasks) {
			set.addTask(task.cloneTask());
		}
		return set;
	}

}
